package com.softstao.guoyu.base;

import android.content.Context;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.os.IBinder;
import android.support.annotation.Nullable;
import android.util.DisplayMetrics;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.webkit.CookieManager;
import android.webkit.CookieSyncManager;
import android.widget.EditText;

import com.igexin.sdk.PushManager;
import com.readystatesoftware.systembartint.SystemBarTintManager;
import com.softstao.guoyu.R;
import com.softstao.guoyu.accept.Accept;
import com.softstao.guoyu.accept.AcceptType;
import com.softstao.guoyu.global.AppManager;
import com.softstao.guoyu.global.SharePreferenceManager;
import com.softstao.guoyu.global.UserManager;
import com.softstao.guoyu.mvp.events.ActionEvent;
import com.softstao.guoyu.mvp.events.NetWorkEvent;
import com.softstao.guoyu.mvp.rxbus.RxBusAnnotationManager;
import com.softstao.guoyu.ui.activity.LoginActivity;
import com.softstao.guoyu.widget.DemoIntentService;
import com.softstao.guoyu.widget.DemoPushService;
import com.softstao.softstaolibrary.library.utils.LZUtils;
import com.softstao.softstaolibrary.library.widget.LZToast;
import com.softstao.softstaolibrary.library.widget.TitleBar;
import com.umeng.analytics.MobclickAgent;
import com.wangjie.androidbucket.customviews.borderscrollview.OnScrollChangedListener;
import com.wangjie.androidbucket.log.Logger;

import java.lang.reflect.Field;
import java.lang.reflect.Method;

import butterknife.BindView;
import butterknife.ButterKnife;
import in.srain.cube.views.ptr.PtrDefaultHandler2;
import in.srain.cube.views.ptr.PtrFrameLayout;
import in.srain.cube.views.ptr.PtrHandler2;
import in.srain.cube.views.ptr.PtrUIHandler;
import in.srain.cube.views.ptr.header.StoreHouseHeader;

public abstract class BaseActivity extends ParentActivity implements PtrHandler2,OnScrollChangedListener{
    private static final String TAG = BaseActivity.class.getSimpleName();
    protected RxBusAnnotationManager rxBusAnnotationManager;
    protected TitleBar titleBar;
    protected SystemBarTintManager tintManager ;
    @Nullable
    @BindView(R.id.ptr_frame)
    protected PtrFrameLayout ptrFrameLayout;
    protected int pageSize = 8;
    protected int offset = 1;
    protected int currentPage = 1;
    private int yScroll=0;
    private int imageHeight ;
    private boolean is_can=false;
    /**
     * 颜色的红绿蓝
     */
    private int red;
    private int green;
    private int blue;
    public PtrFrameLayout getPtrFrameLayout() {
        return ptrFrameLayout;
    }


    @Override
    public void parserMethodAnnotations(Method method) throws Exception {
        if (method.isAnnotationPresent(Accept.class)) {
            if (null == rxBusAnnotationManager) {
                rxBusAnnotationManager = new RxBusAnnotationManager(this);
            }
            rxBusAnnotationManager.parserObservableEventAnnotations(method);
        }
    }
    public void initTitle(String title) {
        titleBar = (TitleBar) getSupportFragmentManager().findFragmentById(R.id.title);
        titleBar.setThemeColor(getResources().getColor(R.color.colorPrimary));
        titleBar.setBackgroundColor(getResources().getColor(R.color.colorPrimary));
        titleBar.getDivider().setVisibility(View.VISIBLE);
        titleBar.setLeftIcon(R.mipmap.back);
        titleBar.setFontColor(getResources().getColor(R.color.font_black));
        titleBar.setBackButtonVisible();
        ViewGroup.MarginLayoutParams lp = (ViewGroup.MarginLayoutParams) titleBar.getMainView().getLayoutParams();
        lp.setMargins(0,tintManager.getConfig().getStatusBarHeight(),0,0);
        titleBar.setTitle(title);
    }

    public abstract int _ContentView();
    public abstract void initView();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(_ContentView());
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
        ButterKnife.bind(this);
        tintManager = new SystemBarTintManager(this);
        tintManager.setStatusBarTintEnabled(true);
        tintManager.setNavigationBarTintEnabled(true);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            tintManager.setTintColor(getResources().getColor(R.color.colorPrimary));
        }
        initView();
        AppManager.getAppManager().addActivity(this);
        imageHeight= LZUtils.dipToPix(context,140);
        if(!setMiuiStatusBarDarkMode(true)){
            FlymeSetStatusBarLightMode(getWindow(),true);
        }
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
        PushManager.getInstance().initialize(this.getApplicationContext(), DemoPushService.class);
        PushManager.getInstance().registerPushIntentService(this.getApplicationContext(), DemoIntentService.class);
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (null == rxBusAnnotationManager) {
            rxBusAnnotationManager = new RxBusAnnotationManager(this);
        }
        if (rxBusAnnotationManager!=null){
            try {
                Method method = this.getClass().getMethod("netWorkError",Object.class,NetWorkEvent.class);
                rxBusAnnotationManager.parserObservableEventAnnotations(method);
                Method method2 = this.getClass().getMethod("error",Object.class,Object.class);
                rxBusAnnotationManager.parserObservableEventAnnotations(method2);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        MobclickAgent.onResume(this);
        PushManager.getInstance().turnOnPush(this);
    }

    @Override
    protected void onPause() {
        super.onPause();
        if (null != rxBusAnnotationManager) {
            rxBusAnnotationManager.clear();
        }
        MobclickAgent.onPause(this);
    }

    @Override
    protected void onStop() {
        super.onStop();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (null != rxBusAnnotationManager) {
            rxBusAnnotationManager.clear();
        }
        AppManager.getAppManager().finishActivity(this);
    }

    //通过RxBus返回的信息
    @Accept
    public void netWorkError(Object tag, NetWorkEvent netWorkEvent) {
//        showToastMessage("网络错误，错误信息："+netWorkEvent.getStrMsg());
        showToastMessage("网络有点不给力哦～请稍后再试吧");
    }

    @Accept(
            value = {
                    @AcceptType(tag = ActionEvent.ERROR , clazz = String.class),
                    @AcceptType(tag = ActionEvent.NO_LOGIN ,clazz = String.class),
                    @AcceptType(tag = ActionEvent.REFRESH_OR_LOAD_FINISH , clazz = String .class)
            }
    )
    public void error(Object tag, Object event){
        switch (tag.toString()){
            case ActionEvent.ERROR:
//                showToastMessage(event.toString());
                error(event.toString());
                break;
            case ActionEvent.REFRESH_OR_LOAD_FINISH:
                if(ptrFrameLayout!=null){
                    ptrFrameLayout.refreshComplete();
                    ptrFrameLayout.requestLayout();
                }
                break;
        }
    }

    protected void error(String msg){
        LZToast.getInstance(this).showToast(msg);
        if(msg.equals("该账号已在其他设备登录")) {
            CookieSyncManager.createInstance(getApplicationContext());
            CookieManager.getInstance().removeAllCookie();
            SharePreferenceManager.getInstance().setCookie("");
            UserManager.getInstance().setUser(null);
            SharePreferenceManager.getInstance().setLoginInfo(null);
            Intent intent = new Intent(this, LoginActivity.class);
            startActivity(intent);
        }
    }

    public int getScreenWidth() {
        DisplayMetrics displaymetrics = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(displaymetrics);
        int width = displaymetrics.widthPixels;
        return width;
    }

    public int getScreenHeight(){
        DisplayMetrics displaymetrics = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(displaymetrics);
        int height = displaymetrics.heightPixels;

        return height;
    }
    protected void setPtrFrameLayoutEnable(){
        StoreHouseHeader header = new StoreHouseHeader(getContext());
        header.setPadding(0, 55, 0, 55);
        header.initWithString(getString(R.string.app_name_en));
        header.setTextColor(getResources().getColor(R.color.theme_color));
        header.setScale(1.7f);
        header.onUIReset(ptrFrameLayout);
        ptrFrameLayout.setHeaderView(header);
        ptrFrameLayout.addPtrUIHandler(header);
        ptrFrameLayout.setPtrHandler(this);
    }

    protected void setPtrFrameLayoutFooter(){
        StoreHouseHeader footer = new StoreHouseHeader(getContext());
        footer.setPadding(0, 50, 0, 50);
        footer.initWithString(getString(R.string.app_name_en));
        footer.setTextColor(getResources().getColor(R.color.theme_color));
        footer.setScale(1.7f);
        footer.onUIReset(ptrFrameLayout);
        ptrFrameLayout.setFooterView(footer);
        ptrFrameLayout.addPtrUIHandler(footer);
    }

    @Override
    public void onLoadMoreBegin(PtrFrameLayout frame) {
        onLoad();
        frame.postDelayed(new Runnable() {
            @Override
            public void run() {
                ptrFrameLayout.refreshComplete();
                ptrFrameLayout.requestLayout();
            }
        }, 1800);
    }

    @Override
    public void onRefreshBegin(PtrFrameLayout frame) {
        onRefresh();
        frame.postDelayed(new Runnable() {
            @Override
            public void run() {
                ptrFrameLayout.refreshComplete();
                ptrFrameLayout.requestLayout();
            }
        }, 1800);
    }

    @Override
    public boolean checkCanDoRefresh(PtrFrameLayout frame, View content, View header) {
        return PtrDefaultHandler2.checkContentCanBePulledDown(frame, content, header);
    }

    @Override
    public boolean checkCanDoLoadMore(PtrFrameLayout frame, View content, View footer) {
        return PtrDefaultHandler2.checkContentCanBePulledUp(frame, content, footer);
    }

    //不足
    protected void setHeaderView(View header){
        ptrFrameLayout.setHeaderView(header);
        ptrFrameLayout.addPtrUIHandler((PtrUIHandler) header);
    }

    protected void setFooterView(View footer){
        ptrFrameLayout.setFooterView(footer);
        ptrFrameLayout.addPtrUIHandler((PtrUIHandler) footer);
    }

    public void onRefresh(){
//        emptyLayout.setVisibility(View.GONE);
        currentPage = 1;
        offset = 1;
    }

    public void onLoad(){
//        emptyLayout.setVisibility(View.GONE);
        currentPage++;
        offset = currentPage * pageSize;
    }

    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        if (ev.getAction() == MotionEvent.ACTION_DOWN) {
            View v = getCurrentFocus();
            if (isShouldHideKeyboard(v, ev)) {
                hideKeyboard(v.getWindowToken());
            }
        }
        return super.dispatchTouchEvent(ev);
    }

    /**
     * 根据EditText所在坐标和用户点击的坐标相对比，来判断是否隐藏键盘，因为当用户点击EditText时则不能隐藏
     *
     * @param v
     * @param event
     * @return
     */
    private boolean isShouldHideKeyboard(View v, MotionEvent event) {
        if (v != null && (v instanceof EditText)) {
            int[] l = {0, 0};
            v.getLocationInWindow(l);
            int left = l[0],
                    top = l[1],
                    bottom = top + v.getHeight(),
                    right = left + v.getWidth();
            if (event.getX() > left && event.getX() < right
                    && event.getY() > top && event.getY() < bottom) {
                // 点击EditText的事件，忽略它。
                return false;
            } else {
                return true;
            }
        }
        // 如果焦点不是EditText则忽略，这个发生在视图刚绘制完，第一个焦点不在EditText上，和用户用轨迹球选择其他的焦点
        return false;
    }

    /**
     * 获取InputMethodManager，隐藏软键盘
     * @param token
     */
    private void hideKeyboard(IBinder token) {
        if (token != null) {
            InputMethodManager im = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
            im.hideSoftInputFromWindow(token, InputMethodManager.HIDE_NOT_ALWAYS);
        }
    }

    @Override
    public void onScrollChanged(int i, int i1, int i2, int i3) {
        yScroll=i1;
        if(is_can){
            if (i1 <= 0) {
                titleBar.setBackgroundColor(Color.TRANSPARENT);//AGB由相关工具获得，或者美工提供
            } else if (i1 > 0 && i1 <= imageHeight) {
                float scale = (float) i1 / imageHeight;
                float alpha = (255 * scale);
                // 只是layout背景透明(仿知乎滑动效果)
                titleBar.setBackgroundColor(Color.argb((int) alpha,  red, green, blue));
            } else {
                titleBar.setBackgroundColor(Color.argb((int) 255,  red, green, blue));
            }
        }
    }

    @Override
    public void onScrollTop() {
    }

    @Override
    public void onScrollBottom() {
        onLoad();
    }

    public int getImageHeight() {
        return imageHeight;
    }

    public void setImageHeight(int imageHeight) {
        this.imageHeight = imageHeight;
    }

    public boolean is_can() {
        return is_can;
    }

    public void setIs_can(boolean is_can) {
        this.is_can = is_can;
    }

    public boolean setMiuiStatusBarDarkMode(boolean darkmode) {
        Class<? extends Window> clazz = getWindow().getClass();
        try {
            int darkModeFlag = 0;
            Class<?> layoutParams = Class.forName("android.view.MiuiWindowManager$LayoutParams");
            Field field = layoutParams.getField("EXTRA_FLAG_STATUS_BAR_DARK_MODE");
            darkModeFlag = field.getInt(layoutParams);
            Method extraFlagField = clazz.getMethod("setExtraFlags", int.class, int.class);
            extraFlagField.invoke(getWindow(), darkmode ? darkModeFlag : 0, darkModeFlag);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

    public static boolean FlymeSetStatusBarLightMode(Window window, boolean dark) {
        boolean result = false;
        if (window != null) {
            try {
                WindowManager.LayoutParams lp = window.getAttributes();
                Field darkFlag = WindowManager.LayoutParams.class
                        .getDeclaredField("MEIZU_FLAG_DARK_STATUS_BAR_ICON");
                Field meizuFlags = WindowManager.LayoutParams.class
                        .getDeclaredField("meizuFlags");
                darkFlag.setAccessible(true);
                meizuFlags.setAccessible(true);
                int bit = darkFlag.getInt(null);
                int value = meizuFlags.getInt(lp);
                if (dark) {
                    value |= bit;
                } else {
                    value &= ~bit;
                }
                meizuFlags.setInt(lp, value);
                window.setAttributes(lp);
                result = true;
            } catch (Exception e) {

            }
        }
        return result;
    }

    @Override
    public void onInjectFailed(Exception e) {
        Logger.e(TAG, "inject failed!!: ", e);
    }

    @Override
    public Resources getResources() {
        Resources resources = super.getResources();
        Configuration configuration = new Configuration();
        configuration.setToDefaults();
        resources.updateConfiguration(configuration, resources.getDisplayMetrics());
        return resources;
    }
}